package com.sys.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sys.entity.User;
import com.sys.exception.DuplicateNameException;
import com.sys.pojo.JsonResult;
import com.sys.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@WebServlet("/reg")
@MultipartConfig
public class RegistServlet extends HttpServlet {

    public static final String UPLOAD = "/upload";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Part head = req.getPart("head");
        // 此路径是头像路径，保存到数据库中，如：/upload/a0ad7e629a624b49b71d850d2feee9df.png
        String fileDB = null;
        if(head!=null) {
            // 上传文件才执行下面代码
            if(head.getSubmittedFileName()!=null && !"".equals(head.getSubmittedFileName())) {
                // 在当前工程下创建upload文件夹
                // upload文件夹的绝对路径（全路径）
                String upload = req.getServletContext().getRealPath(UPLOAD);
                File uploadFile = new File(upload);
                if (!uploadFile.exists()) {
                    // 创建文件夹
                    uploadFile.mkdirs();
                }

                String uuid = UUID.randomUUID().toString().replace("-", "");
                //截取文件后缀
                // 从右往左找 最后一个  .
                int pos = head.getSubmittedFileName().lastIndexOf(".");
                // 截取后缀
                String suffix = head.getSubmittedFileName().substring(pos);
                // 拼装新文件名，uuid+原文件名的后缀
                String newFileName = uuid+suffix;

                fileDB = UPLOAD+"/"+newFileName;
                // 拼装的是保存上传文件的全路径
                File file = new File(uploadFile,newFileName );
                // 保存
                head.write(file.getAbsolutePath());

                //文件名称
                System.out.println(head.getSubmittedFileName());
                //文件大小
                System.out.println(head.getSize());
            }
        }

        // 通过request对象获取浏览器提交的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = new User();
        user.setUsername(username);
        user.setUpassword(password);
        if(fileDB!=null) {
            user.setHead(fileDB);
        }

        UserService service = new UserService();
        PrintWriter writer = resp.getWriter();
        JsonResult jr = new JsonResult();

        try {
            service.regist(user);

            jr.setCode(0);
            jr.setMsg("注册成功！");
        } catch (DuplicateNameException e){
            jr.setCode(103);
            jr.setMsg(e.getMessage());
        } catch (Exception e) {
            jr.setCode(500);
            jr.setMsg("服务器发生错误");
            e.printStackTrace();
        }

        //将java对象，转换成 json 格式的字符串
        ObjectMapper om=new ObjectMapper();
        String json=om.writeValueAsString(jr);
        writer.write(json);
        writer.close();//关闭

    }
}
